﻿using Net;
using Net.AOI;
using Net.Entities;
using Net.Share;

namespace AOITest
{
    public class GridUnit : IGridObject, IGridUpdate
    {
        public long Identity { get; set; }
        public Vector3 Position { get; set; }
        public Grid Grid { get; set; }
        public bool MainRole { get; set; }

        public Vector3 Destination;

        public void OnInit()
        {
            Destination = new Vector3(RandomHelper.Range(-1000, 1000), 0, RandomHelper.Range(-1000, 1000));
        }

        public void OnEnter(IGridObject gridObject)
        {
        }

        public void OnExit(IGridObject gridObject)
        {
        }

        public void OnEnterGrid(Grid enterGrid)
        {
        }

        public void OnLeaveGrid(Grid leaveGrid)
        {
        }

        public void OnUpdate()
        {
            Vector3 avoidance = Vector3.zero;
            int count = 0;
            float avoidRadius = 2.0f; // 避障半径

            foreach (var neighbor in Grid)
            {
                if (neighbor is GridUnit other && other.Identity != Identity)
                {
                    float dist = Vector3.Distance(Position, other.Position);
                    if (dist < avoidRadius && dist > 0.01f)
                    {
                        // 计算避让方向
                        avoidance += (Position - other.Position).normalized / dist;
                        count++;
                    }
                }
            }

            Vector3 targetDir = (Destination - Position).normalized;
            Vector3 moveDir = targetDir;

            if (count > 0)
            {
                // 合成目标方向和避障方向
                avoidance = (avoidance / count).normalized;
                moveDir = (targetDir + avoidance * 1.5f).normalized;
            }

            Position += moveDir * 6f * Time.deltaTime;
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            var world = new GridWorld();
            world.Init(-500, -500, 50, 50, 20, 20);

            int totalUnits = 100_000;
            int rowLength = (int)Math.Ceiling(Math.Sqrt(totalUnits)); // 每行单位数
            float spacing = 1.0f; // 单位间距

            for (int i = 0; i < totalUnits; i++)
            {
                int x = i % rowLength;
                int z = i / rowLength;
                var unit = new GridUnit
                {
                    Position = new Vector3(x * spacing, 0, z * spacing) // y=0
                };
                world.Insert(unit);
            }

            var dateTime = DateTime.Now.AddSeconds(1);
            int fps = 0;
            while (true)
            {
                world.Update();
                fps++;
                if (DateTime.Now >= dateTime)
                {
                    Console.Title = "FPS:" + fps;
                    dateTime = DateTime.Now.AddSeconds(1);
                    fps = 0;
                }
            }
        }
    }
}
